(function($) {
    function AGrid(el, options) {
        this.el = $(el);
        this.options = {
            tableId: '',
            pagerId: '',
            page: 1,
            rows: 10,
            total: 0,
            url: '',
            type: 'pagination',
            loadingMessage: "Loading..."
        };
        this.setOptions(options);
        this.initialize();
    }
  
    $.fn.aGrid = function(options) {
        return new AGrid(this.get(0), options);
    };


    AGrid.prototype = {
        initialize: function() {
            var me;
            me = this;
            this.options.tableId = "#"+$(this.el).attr('id');
            me.loadPage(me.options.page);
        },
        reload: function(){
            this.loadPage(this.options.page);
        },
        loadPage: function(page){
            var me = this.options;
            me.page = page;
            var o = this;
            var req = {};
            req.page = me.page;
            req.rows = me.rows;
            $(o.el).after("<div class='agrid-loader'>"+me.loadingMessage+"</div>");
            $.ajax({
                url: me.url,
                dataType: 'json',
                type: 'POST',
                data: req,
                success: function(data){
                    $('.agrid-loader').remove();
                    if(data.result =='1'){
                        me.page = parseInt(data.page);
                        me.total = parseInt(data.total);
                        $(me.tableId).html(data.message);
                    }else{
                        alert('Erroare!');
                    }
                    if(me.pagerId != '' && $(me.pagerId).size() > 0){
                        o.initPager();
                    }
                }
            });
        },
        initPager: function(){
            var o = this;
            var me = this.options;
            $(me.pagerId).each(function(){
                var obj = this;
                var str = "<ul id='ul-pager'>";
                var tp = Math.round(me.total/me.rows)+1;
                str += "<li><a href='javascript:void(0);' class='prev'>Prev</a></li>";
                for(var i = 1; i < tp; i++){
                    if((i) != me.page){
                        str += "<li> <a href='javascript:void(0);' id='"+(i)+"' class='pg'>"+(i)+"</a></li>";
                    }else{
                        str += "<li>"+(i)+"</li>";
                    }
                }
                str += "<li><a href='javascript:void(0);' class='next'>Next</a></li>";
                str +="</ul>";
                $(obj).html(str);
                $("#ul-pager li a.next",obj).click(function(){
                    if((parseInt(me.page)+1) < tp){
                        o.loadPage(me.page+1);
                    }
                });
                $("#ul-pager li a.prev",obj).click(function(){
                    if(me.page-1 >= 1){
                        o.loadPage(me.page-1);
                    }
                });
                $("#ul-pager li a.pg",obj).click(function(){
                    o.loadPage($(this).attr('id'));
                });
            });
        },
        setOptions: function(options){
            var o = this.options;
            $.extend(o, options);
        }

    };

}(jQuery));

function mapSendForm(formId, table, urlSend, urlForm){
    if($(formId).children().size() == 0){
        $(formId).after("<div class='agrid-loader'>Loading...</div>");
        $.ajax({
            url: urlForm,
            dataType: 'json',
            type: 'POST',
            success: function(data){
                $('.agrid-loader').remove();
                if(data.result =='1'){
                    $(formId).html(data.message);
                    $(formId+" #send").click(function(){
                        sendForm(formId, table, urlSend);
                    });
                    $(formId+" #cancel").click(function(){
                        $(formId + " input, "+formId+" select, "+formId+" textarea").not(formId+" input[type='checkbox']").val('');
                        $(formId+" input[type='checkbox']").removeAttr('checked');
                    });
                }else{
                    alert('Problem with loading Send Message Form!');
                }
            }
        }); 
    }
    
}
function sendForm(formId, table, urlSend){
    $(formId).after("<div class='agrid-loader'>Loading...</div>");
    $.ajax({
        url: urlSend,
        dataType: 'json',
        type: 'POST',
        data: $(formId).serialize(),
        success: function(data){
            $('.agrid-loader').remove();
            if(data.result =='1'){
                $(formId+" #errors").html(data.message);
            }else{
                $(formId+" #errors").html(data.message);
            }
            table.reload();
        }
    });
}
$(function(){
    var tbl = $('#messages').aGrid({
        tableId: '#messages',
        pagerId: '#messages_pager',
        page: 1,
        rows: 10,
        total: 0,
        url: base_url+"mltv/getMessagesByPages/",
        type: 'pagination'
    });
    tbl.reload();
    var urlSend = base_url+"mltv/sendMessage/";
    var urlForm = base_url+"mltv/getSendForm/";
    mapSendForm('#sendMessageForm', tbl, urlSend, urlForm);
});